using System;
using System.Linq;
using SharePoint.Security.ConfigAnalyzer.Engine.Base;
using SharePoint.Security.ConfigAnalyzer.Engine.Common;
using Microsoft.SharePoint.Administration;

namespace SharePoint.Security.ConfigAnalyzer.Engine.Rules.Diagnostic
{
    public class LoggingTraceFileLocation : BaseRule
    {
        public LoggingTraceFileLocation()
        {
            RuleInfo = new RuleInfo
                           {
                               Title = "Logging trace file location",
                               Description = "Ensure Trace log files are configured to a Non-system drive Diagnostic Logging (Central Admin > Monitoring> Diagnostic Logging > Metrics.aspx)",
                               ExpectedValue =
                                   String.Format("Should not be on system drive {0}",
                                                 Environment.SystemDirectory.Split("\\".ToArray())[0])
                           };
        }

        #region Overrides of BaseRule

        public override void Validate()
        {

            SPDiagnosticsService diagSvc = ObjectHelper.Diagnostics;
            string ulsLogLocation = diagSvc.LogLocation;

            if (ulsLogLocation.Contains("%"))
            {
                var result = ulsLogLocation.Split("%".ToArray());

                if (result.Count() == 3)
                {
                    ulsLogLocation = string.Format("{0}{1}", Environment.GetEnvironmentVariable(result[1]), result[2]);
                }
            }

            var systemDrive = Environment.SystemDirectory.Split("\\".ToArray())[0];

            if (ulsLogLocation.StartsWith(systemDrive))
            {
                Status = Status.Fail;
            }
            else
            {
                Status = Status.Fail;
            }

            CurrentValue = ulsLogLocation;
        }

        #endregion
    }
}